/**
 * @author Quixn
 * @description
 * 快速导出压缩包 需要安装依赖 npm install archiver -D
 * 这个库的文档地址 https://github.com/archiverjs/node-archiver
 * 可以在 package.json 中配置 script 命令 npm run build 之后直接 进行 导出 zip 压缩包
 * @example  将需要导出的目录添加到target数组中 命令行执行 node export-zip.js 即可
 * @version 20220622
 */
const fs = require('fs');
const path = require('path');
const archiver = require('archiver');
const process = require('process');

const inputDir = 'dist';
const distFile = 'dist.zip';
let inputList = [];                 //配置要打包的路径列表，需要打包某些目录，添加到数组里面即可，相对路径

// 目录分隔符
let DIR_SEPARATOR = '';
if (process.platform == 'win32') {
    DIR_SEPARATOR = '\\';
} else {
    DIR_SEPARATOR = '/';
}

// 读取目录中的文件与文件夹，添加到 inputList 列表中
const files = fs.readdirSync(inputDir);
for (let f of files) {
    let cur = {};
    cur.name = f;
    let filepath1 = inputDir + '/' + f;
    let stat = fs.statSync(filepath1)
    if (stat.isFile()) {
        cur.type = 'file';
        //console.log('文件:' + f);
        let ext = path.extname(f).toLowerCase();
        //console.log('后缀:' + ext);
        if (ext == '.zip') {                    // 忽略.zip文件，避免zip自己压缩自己 
            continue;
        }
    } else {
        cur.type = 'dir';
        //console.log('目录:' + f);
    }
    inputList.push(cur);
}

let rootDir = process.cwd();
process.chdir(rootDir + '/' + inputDir);
let workDir = process.cwd();

//console.log('root dir = ' + rootDir);
//console.log('work dir = ' + workDir);

// 默认在当前目录路径生成zip文件 
const output = fs.createWriteStream(workDir + '/' + distFile);
const archive = archiver('zip', {
    zlib: { level: 9 } // 设置压缩级别
});

archive.on('error', function (err) {
    throw err;
});

output.on('close', function () {
    console.log(`
  ------------------压缩完毕------------------
    生成文件大小 ${(archive.pointer() / 1024 / 1024).toFixed(2)} MB
    请在 ${inputDir} 下寻找 ${distFile} 文件
    路径为 ${workDir}${DIR_SEPARATOR}${distFile}
  ------------------压缩完毕------------------
    `);

    // 回到原来的 root 目录
    process.chdir(rootDir);
    //console.log('curr dir = ' + process.cwd());
});

archive.pipe(output);

console.log('');
for (let input of inputList) {
    if (input.type == 'dir') {
        archive.directory(input.name, input.name);
        console.log('压缩: ' + input.name);
    } else {
        archive.file(input.name);
        console.log('压缩: ' + input.name);
    }
}


archive.finalize();

